

(function ($, win, doc, body) {
    var supportedClient = true,
        jqTemplateId = "jqTemplateActionGroup",
        openedClassname = "tl-acngroup-opened",
        disabledClassname = "disabled",
        $body = $(body);

    // check client
    supportedClient = true;

    // callbacks
    function onBodyClick (evt) {
        $body.unbind("click", onBodyClick).find("div." + openedClassname)
          .removeClass(openedClassname).find("div.menu-container").hide();
    }

    function onTitleClick (evt) {
        onBodyClick();
        var $acngroup = $(this).parents('div.action-group:first');

        if ($acngroup.hasClass(openedClassname) || $acngroup.hasClass(disabledClassname)) {
          return undefined;
        }

        $acngroup.addClass(openedClassname).find("div.menu-container:first").show();
        setTimeout(bindBodyEvents, 0);
    }

    function bindBodyEvents () {
        $body.bind("click", onBodyClick);
    }

    function bindEvents ($acngroup) {
        $acngroup.find("div.menu-title:first")
          .bind("click", onTitleClick);
    }

    function initActionGroup ($btns) {
        var $acngroup = $.tlTmpl(jqTemplateId, {});
        $btns.filter(":first").before($acngroup);
        $acngroup.find("div.menu-list:first").append($btns);

        bindEvents($acngroup);
    }

    $.fn.tlActionGroup = function () {
        if (supportedClient && this.is('button')) {
            initActionGroup(this);
        }

        return this;
    };
})(jQuery, window, document, document.body);
